package com.czz.ucenter.controller;

import com.czz.common.exception.ResultCodeEnum;
import com.czz.common.vo.R;
import com.czz.ucenter.config.JwtProperties;
import com.czz.ucenter.entity.Admin;
import com.czz.ucenter.service.AdminService;
import com.czz.ucenter.service.KaptchaService;
import com.czz.ucenter.utils.CookieUtils;
import com.czz.ucenter.utils.JwtUtils;
import com.czz.ucenter.vo.AdminInfoVo;
import com.czz.ucenter.vo.KaptchaVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: AdminController
 * @Author Czz
 * @Date 2019/12/24
 * @Time 9:49
 **/
@RestController
@RequestMapping(value = "/admin/admins")
public class AdminController {

    @Autowired
    AdminService adminService;

    @Autowired
    KaptchaService kaptchaService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    static final String TOKEN_PREFIX = "admin:token:";

    /**
    * @Description 管理员登录
    * @Param [username, password, request, response]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2019/12/24
    * @Time 10:46
    **/
    @PostMapping(value = "/login")
    public R login(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String codeImg,
            @RequestParam String codeToken,
            HttpServletRequest request,
            HttpServletResponse response){

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(codeImg) || StringUtils.isEmpty(codeToken)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }

        //先判断验证码
        KaptchaVo kaptchaVo = new KaptchaVo();
        kaptchaVo.setCodeImg(codeImg);
        kaptchaVo.setCodeToken(codeToken);
        Integer flag = kaptchaService.checkVerifyCode(kaptchaVo);

        if (flag.equals(1)) return R.error().message("验证码过期，请刷新验证码");
        if (flag.equals(2) || flag == null) return R.error().message("验证码输入错误，请重新输入");


        //再判断账号密码
        Admin admin = adminService.login(username,password);
        if (ObjectUtils.isEmpty(admin)){
            return R.setResult(ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        String token = JwtUtils.generateJWT(admin);
        //存入cookies,token和cookies有效期都为60分钟
        //CookieUtils.setCookie(request,response, JwtProperties.ADMINNAME,token,JwtProperties.MANAGEEXPIRE*60,null,false);

        //token存入redis，用户过期时间720分钟，12小时
        this.redisTemplate.opsForValue().set(TOKEN_PREFIX + admin.getId(), token, JwtProperties.MANAGEEXPIRE, TimeUnit.MINUTES);
        return R.ok().data("token",token);
    }

    /**
    * @Description 根据token解析管理员信息
    * @Param [token]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2019/12/24
    * @Time 10:47
    **/
    @GetMapping(value = "/verify")
    public R getAdminInfoByJwt(HttpServletRequest request){
        String token = request.getHeader("ADMIN-TOKEN");

        if (StringUtils.isEmpty(token)){
            return R.setResult(ResultCodeEnum.UNAUTHORIZED);
        }

        Claims claims = JwtUtils.checkJWT(token);

        String id = (String) claims.get("id");
        String mobile = (String) claims.get("mobile");
        String name = (String) claims.get("name");

        AdminInfoVo adminInfoVo = new AdminInfoVo();
        adminInfoVo.setId(id);
        adminInfoVo.setMobile(mobile);
        adminInfoVo.setName(name);

        String redisToken = this.redisTemplate.opsForValue().get(TOKEN_PREFIX + id);

        if (ObjectUtils.isEmpty(adminInfoVo) || StringUtils.isEmpty(redisToken) || !token.equals(redisToken)){
            return R.setResult(ResultCodeEnum.UNAUTHORIZED);
        }

        return R.ok().data("userInfo",adminInfoVo);
    }

    /**
    * @Description 修改管理员密码
    * @Param [id, oldPassword, newPassword]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/3/12
    * @Time 10:42
    **/
    @PutMapping(value = "{id}")
    public R updatePassword(@PathVariable String id,String oldPassword,String newPassword){
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        adminService.updatePassword(id,oldPassword,newPassword);
        return R.ok();
    }

    /**
    * @Description 管理员注销
    * @Param [adminId]
    * @Return com.czz.common.vo.R
    * @Author Czz
    * @Date 2020/3/21
    * @Time 18:48
    **/
    @PostMapping(value = "/logout")
    public R logout(String adminId){
        if (StringUtils.isEmpty(adminId)){
            return R.setResult(ResultCodeEnum.INPUT_ERROR);
        }
        //删除redis中token
        this.redisTemplate.delete(TOKEN_PREFIX + adminId);
        return R.ok();
    }
}
